import pdfplumber
from docx import Document
from pptx import Presentation
import pandas as pd
from PIL import Image
import pytesseract
import os


def extract_text_from_pdf(pdf_path):
    """从PDF文件中提取文本"""
    text = ''
    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            text += page.extract_text() or ''
    return text


def extract_text_from_docx(docx_path):
    """从DOCX文件中提取文本"""
    doc = Document(docx_path)
    return '\n'.join([paragraph.text for paragraph in doc.paragraphs if paragraph.text])


def extract_text_from_pptx(pptx_path):
    """从PPTX文件中提取文本"""
    prs = Presentation(pptx_path)
    text = ''
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape, "text"):
                text += shape.text + '\n'
    return text


def extract_text_from_excel(xlsx_path):
    """从Excel文件中提取文本"""
    xl = pd.ExcelFile(xlsx_path)
    text = ''
    for sheet_name in xl.sheet_names:
        df = xl.parse(sheet_name)
        text += ' '.join(df.astype(str).values.flatten()) + '\n'
    return text


def extract_text_from_image(image_path):
    """使用OCR从图像中提取文本"""
    return pytesseract.image_to_string(Image.open(image_path))


def extract_text(file_path):
    """根据文件类型提取文本内容"""
    _, file_extension = os.path.splitext(file_path)
    file_extension = file_extension.lower()
    if file_extension == '.pdf':
        return extract_text_from_pdf(file_path)
    elif file_extension == '.docx':
        return extract_text_from_docx(file_path)
    elif file_extension == '.pptx':
        return extract_text_from_pptx(file_path)
    elif file_extension in ['.xls', '.xlsx']:
        return extract_text_from_excel(file_path)
    elif file_extension in ['.png', '.jpg', '.jpeg']:
        return extract_text_from_image(file_path)
    else:
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                return file.read()
        except UnicodeDecodeError:
            return ''
